
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.ArrayList;



public class Server implements Runnable {
	public static String message = null;
	public static String ok_message = null;
   DatagramSocket theSocket = null;
   
   public Server () {      
      
      try {
         theSocket = new DatagramSocket(1235);
         //System.out.println("Server created and waiting for incomming connections...");
      } catch (SocketException e) {
         // TODO Auto-generated catch block
         System.out.println("Error creating the socket: " + e.getMessage());
      }
   }
   
   public void run() {
      
      DatagramPacket theRecievedPacket;
      byte[] inBuffer;
      String try_message = null;
      String type;
	  String msg_id;
	  ArrayList<String> lst_id = new ArrayList<String>();
	  final int max_ids = 15;
      
		lst_id.add("0");
		// create some space for the text to send and recieve data
		inBuffer = new byte[500];
		// create a place for the client to send data too
		theRecievedPacket = new DatagramPacket(inBuffer, inBuffer.length);
		// wait for a client to request a connection
		
		try {
			while (true) {
				theSocket.receive(theRecievedPacket);
				if ( theRecievedPacket != null ) {
					try_message = new String(theRecievedPacket.getData(), 0,theRecievedPacket.getLength());
					System.out.println(try_message);
					type = try_message.split("@")[0];
					System.out.println(type);
					//checa para ver se nao eh soh uma duplicata, uma vez q o android manda varias copias ate o PC confirmar que chego alguma	
					if ( type.contains(MainPc.type)) {
						ok_message = try_message;
					}
					else {
						msg_id = try_message.split("@")[1];
						System.out.println(msg_id);
						System.out.println(lst_id);
						if ( !lst_id.contains(msg_id)) {
							Client.ip = try_message.split("@")[2];
	    					message = try_message.split("@")[3];
	    					lst_id.add(msg_id);
							if (lst_id.size() > max_ids )
								lst_id.remove(0);
						}
						//mesmo que for uma duplicata eh bom mandar o check para dizer ao programa do PC que o android recebeu a String
						Client.enviar(try_message, type);
					}
				}
			} 
		} catch (IOException ExceIO){
			System.out.println("Error with client request : "+ExceIO.getMessage());
		}
      
      // close the server socket
   }
}
